﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using DataAssociations.Repository.Connection.RDBMSSchemaExplorer;

namespace DataAssociations
{
    public class RunOptions
    {
        public string TextBoxPath { get; set; }
        public string ComboBoxAlgorithm { get; set; }
        public int TextBoxSupport { get; set; }
        public int TextBoxConfidence { get; set; }
        public DatabaseMetadataOptions DatabaseMetadata { get; set; }

        public bool IsApriori { get { return ComboBoxAlgorithm.Contains("Apriori"); } }
    }

    public class OptionsFileReader
    {
        public OptionsFileReader()
        {
            string[] lines = File.ReadAllLines(_textBoxFileName);
            var dictionary = new Dictionary<string, string>();
            foreach (var line in lines)
                if (!string.IsNullOrWhiteSpace(line))
                    dictionary.Add(line.Split(' ')[0], line.Split(' ')[1]);
            Options = new RunOptions();
            Options.TextBoxPath = dictionary[_textBoxPathKey];
            Options.ComboBoxAlgorithm = dictionary[_comboBoxAlgorithmKey];
            if (Options.IsApriori)
                Options.TextBoxSupport = Int32.Parse(dictionary[_textBoxSupportKey]);

            Options.TextBoxConfidence = Int32.Parse(dictionary[_textBoxConfidenceKey]);
        }

        private const string _textBoxFileName = @"Options.txt";
        private const string _textBoxPathKey = "textBoxPath";
        private const string _comboBoxAlgorithmKey = "comboBoxAlgorithm";
        private const string _textBoxSupportKey = "textBoxSupport";
        private const string _textBoxConfidenceKey = "textBoxConfidence";
        public RunOptions Options { get; private set; }

        internal void Persist(RunOptions options)
        {
            var sb = new StringBuilder();
            sb.AppendLine(string.Format("{0} {1}", _textBoxPathKey, options.TextBoxPath));
            if (options.IsApriori)
                sb.AppendLine(string.Format("{0} {1}", _textBoxSupportKey, options.TextBoxSupport));

            sb.AppendLine(string.Format("{0} {1}", _comboBoxAlgorithmKey, options.ComboBoxAlgorithm));

            sb.AppendLine(string.Format("{0} {1}", _textBoxConfidenceKey, options.TextBoxConfidence));
            TextWriter tw = new StreamWriter(_textBoxFileName);

            // write a line of text to the file
            tw.WriteLine(sb.ToString());
            // close the stream
            tw.Close();
        }
    }
}
